package com.aiwu;

import android.text.TextUtils;

import com.aiwu.bean.ConfigBean;
import com.aiwu.bean.InitDataBean;
import com.aiwu.library.AiwuSimulator;
import com.aiwu.library.bean.CheatChildBean;
import com.aiwu.library.bean.CheatGroupBean;
import com.aiwu.library.netWork.BaseBean;
import com.aiwu.library.util.IOUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.callback.AbsCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.ResponseBody;

public abstract class InitCallback extends AbsCallback<BaseBean<InitDataBean>> {

    @Override
    public BaseBean<InitDataBean> convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null)
            return null;
        BaseBean<InitDataBean> data = null;
        try {
            JSONObject jsonObject = JSON.parseObject(body.string());
            int code = jsonObject.getIntValue("Code");
            String message = jsonObject.getString("Message");
            JSONObject dataObject = jsonObject.getJSONObject("Data");
            String romName = "";
            String gameName = "";
            String cheatStr = "";
            ConfigBean configBean = null;
            if (dataObject != null) {
                romName = dataObject.getString("RomName") == null ? "" : dataObject.getString("RomName");
                gameName = dataObject.getString("GameName") == null ? "" : dataObject.getString("GameName");
                cheatStr = dataObject.getString("Cheat") == null ? "" : dataObject.getString("Cheat");
                JSONObject configObject = dataObject.getJSONObject("Config");
                if (configObject != null) {
                    configBean = new ConfigBean();
                    Integer gpu = configObject.getInteger("use_asynchronous_gpu_emulation");
                    configBean.setUseAsynchronousGpuEmulation(gpu == null ? ConfigBean.DEFAULT_VALUE : gpu);
                    Integer acc = configObject.getInteger("shaders_accurate_mul");
                    configBean.setShadersAccurateMul(acc == null ? ConfigBean.DEFAULT_VALUE : acc);
                    Integer region = configObject.getInteger("region_value");
                    configBean.setRegionValue(region == null ? ConfigBean.DEFAULT_VALUE : region);
                    Integer language = configObject.getInteger("language");
                    configBean.setLanguage(language == null ? ConfigBean.DEFAULT_VALUE : language);
                    Integer font = configObject.getInteger("font");
                    configBean.setFont(font == null ? ConfigBean.DEFAULT_VALUE : font);
                    Integer skipSlowDraw = configObject.getInteger("skip_slow_draw");
                    configBean.setSkipSlowDraw(skipSlowDraw== null ? ConfigBean.DEFAULT_VALUE : skipSlowDraw);
                    Integer fmvHack = configObject.getInteger("fmv_hack");
                    configBean.setFmvHack(fmvHack== null ? ConfigBean.DEFAULT_VALUE : fmvHack);
                }
            }
            cheatStr = cheatStr.replace("\\r", "");
            //用户定义的金手指行数
            int customCheatLines = 0;

            //region添加用户定义的金手指
            final String customCheatFilePath = AiwuSimulator.getCheatListener().getCustomCheatFilePath();
            //读取用户定义金手指文本
            String customCheatStr = IOUtil.readFile2String(customCheatFilePath);
            if (!TextUtils.isEmpty(customCheatStr)) {
                cheatStr = customCheatStr + "\n" + cheatStr;
                customCheatLines = customCheatStr.split("\\n").length;
            }
            //endregion

            List<CheatGroupBean> cheatList = new ArrayList<>();
            String[] cheatLines = cheatStr.split("\\n");
            //是否在读子列表
            boolean inListMode = false;
            CheatGroupBean cheatBean = null;
            List<CheatChildBean> childrenList = null;
            for (int i = 0; i < cheatLines.length; i++) {
                String line = cheatLines[i];
                if (line.startsWith("C ")) {
                    if (!line.contains("#")) {
                        continue;
                    }
                    String[] strings = line.split("#");
                    String desc = strings[0].replaceFirst("C ", "");
                    String codes = strings[1];
                    if (inListMode) {
                        if (cheatCodeRegex(codes)) {
                            CheatChildBean bean = new CheatChildBean(desc, codes);
                            childrenList.add(bean);
                        }
                    } else {
                        if (cheatCodeRegex(codes)) {
                            CheatGroupBean bean = new CheatGroupBean(desc, codes, i < customCheatLines, false);
                            cheatList.add(bean);
                        }
                    }
                } else if (line.startsWith("D ") || line.startsWith("F ")) {
                    boolean isCheckbox = line.startsWith("F ");
                    inListMode = true;
                    cheatBean = new CheatGroupBean();
                    cheatBean.setCheckbox(isCheckbox);
                    String desc = line.replace(isCheckbox ? "F " : "D ", "");
                    cheatBean.setDesc(desc);
                    childrenList = new ArrayList<>();
                    cheatBean.setChildren(childrenList);
                } else if (line.startsWith("E")) {
                    inListMode = false;
                    cheatList.add(cheatBean);
                }
            }

            InitDataBean initDataBean = new InitDataBean();
            initDataBean.setRomName(romName);
            initDataBean.setGameName(gameName);
            initDataBean.setCheatList(cheatList);
            initDataBean.setConfig(configBean);

            data = new BaseBean<>();
            data.setCode(code);
            data.setMessage(message);
            data.setData(initDataBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 验证金手指
     *
     * @param cheatCode 金手指
     * @return 是否通过
     */
    private boolean cheatCodeRegex(String cheatCode) {
        if (AiwuSimulator.getCheatListener() != null) {
            String regex = AiwuSimulator.getCheatListener().getNetCheatCodeRegex();
            //如果填写了正则就判断下
            if (!TextUtils.isEmpty(regex)) {
                Pattern p = Pattern.compile(regex);
                String[] lines = cheatCode.toUpperCase().trim().split(",");
                for (String line : lines) {
                    Matcher m = p.matcher(line);
                    if (!m.matches()) {
                        return false;
                    }
                }
                return true;
            }
        }
        return true;
    }
}